//
//  XXTextField.swift
//  XXSwiftDemo
//
//  Created by admin on 2022/3/28.
//

import UIKit

class XXTextField: UITextField,UITextFieldDelegate {
    
    typealias XXTextFieldReturnBlock = ()->Void
    var maxLength:Int = 30 {// 最大输入长度
        didSet{
            self.delegate = self
        }
    }
    var returnBlock:XXTextFieldReturnBlock? {
        didSet{
            self.delegate = self
        }
    }
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string == "" {// 删除
            return true
        }
        let str:String = textField.text ?? ""
        let count:Int = str.count + string.count
        if count <= maxLength {
            return true
        }else{
            return false
        }
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if let b = returnBlock{
            b()
        }
        return true
    }
}
extension XXTextField {
    
    convenience init(frame:CGRect = .zero, color: UIColor = .black, placeholder: String = "", font: UIFont = .system(15)) {
        self.init(frame: frame)
        delegate = self
        textColor = color
        self.font = font
        self.placeholder = placeholder
        self.leftPadding(10)
    }
}
public extension UITextField{
    
    // 设置Placeholder占位符的颜色
    func placeholder(color: UIColor) {
        self.setValue(color, forKey: "placeholderLabel.textColor");
    }
    
    // 设置文字左边留出的空白宽度
    func leftPadding(_ left: CGFloat) {
        self.leftView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: left, height: self.frame.size.height));
        self.leftViewMode = .always;
    }
    
    // 设置文字右边留出的空白宽度
    func rightPadding(_ right: CGFloat) {
        self.rightView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: right, height: self.frame.size.height));
        self.rightViewMode = .always;
    }
}
